import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout/home',
  },
  {
    path: '/detail/:detailId',
    name: 'detail',
    meta: {
      auth: false,
      title: '详情',
    },
    component: () => import('../views/Detail.vue'),
  },
  {
    path: '/about/:aboutId',
    name: 'about',
    meta: {
      auth: false,
      title: '关于',
    },
    component: () => import('../views/keep-alive/about.vue'),
  },
  {
    path: '/khome',
    name: 'khome',
    meta: {
      auth: false,
      title: 'khome',
    },
    component: () => import('../views/keep-alive/home.vue'),
  },

  {
    path: '/layout',
    name: 'layout',
    component: () => import('../layout/index.vue'),
    children: [
      {
        path: 'findMovie',
        name: 'findMovie',
        meta: {
          auth: false,
          title: '找电影',
        },
        component: () => import('../views/FindMovie.vue'),
      },
      {
        path: 'personCenter',
        name: 'personCenter',
        meta: {
          auth: false,
          title: '个人中心',
        },
        component: () => import('../views/PersonCenter.vue'),
      },
      {
        path: 'home',
        name: 'home',
        meta: {
          // 导航元信息
          auth: false, // 需要判断token才能进入页面
          title: '首页',
        },
        component: () => import('../views/HomeView.vue'),
      },
      {
        path: 'collect',
        name: 'collect',
        meta: {
          auth: true,
          title: '收藏',
        },
        component: () => import('../views/Collect.vue'),
      },
    ],
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

// 导航守卫
router.beforeResolve((to, from, next) => {
  if (to.meta.auth) {
    const token = store.state.token
    if (token) {
      next()
    } else {
      next({
        path: '/layout/personCenter',
      })
    }
  } else {
    next()
  }
})

export default router
